<template>
  <!-- 数据采集流程表单弹窗 -->
  <div>
    <el-dialog
      :close-on-click-modal="false"
      v-model="visibleDialog"
      :title="props.title"
      width="1100px"
      draggable
      @close="closeDialog"
      destroy-on-close
    >
      <el-form
        ref="formRef"
        :model="formData"
        :inline="true"
        :rules="rules"
        label-width="120"
      >
        <div>
          <el-row>
            <el-col :span="12">
              <el-form-item label="采集流程编号" prop="flowCode" class="w-full">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.flowCode"
                  placeholder="请输入采集流程编号"
                  style="width: 100%"
                  clearable
                />
                <span v-else>{{ formData.flowCode }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="采集流程名称" prop="flowName" class="w-full">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.flowName"
                  placeholder="请输入采集流程名称"
                  clearable
                />
                <span v-else>{{ formData.flowName }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="设备类型" prop="equipTypeId" class="w-full">
                <el-select
                  style="width: 100%"
                  v-if="!props.isReadonly"
                  v-model="formData.equipTypeId"
                  placeholder="请选择设备类型"
                  @change="deviceTypeChage"
                  clearable
                  filterable
                >
                  <el-option
                    v-for="item in equipTypeList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
                <span v-else>{{ formData.equipTypeName }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="启用状态" prop="enabled" class="w-full">
                <el-radio-group
                  v-if="!props.isReadonly"
                  v-model="formData.enabled"
                >
                  <el-radio :label="1">启用</el-radio>
                  <el-radio :label="0">停用</el-radio>
                </el-radio-group>
                <span v-else>{{
                  formData.enabled === 1 ? "启用" : "停用"
                }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="设备" prop="deviceId" class="w-full">
                <el-select
                  multiple
                  style="width: 100%"
                  v-model="formData.deviceId"
                  placeholder="请选择设备"
                  clearable
                  :disabled="props.isReadonly"
                  filterable
                >
                  <el-option
                    v-for="item in equipList"
                    :key="`${item.id}`"
                    :label="`${item.equipName}`"
                    :value="`${item.id}`"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="备注" prop="remarks" class="w-full">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.remarks"
                  placeholder="请输入备注"
                  clearable
                />
                <span v-else>{{ formData.remarks }}</span>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <div
          style="
            display: flex;
            justify-content: space-between;
            align-items: center;
          "
        >
          <h4 class="mb-[20px] mt-[20px]">采集数据</h4>
          <el-button
            type="success"
            plain
            @click="handleAdd"
            v-if="!props.isReadonly"
          >
            <i-ep-plus />
            新增
          </el-button>
        </div>

        <div class="formTable">
          <el-table
            :data="formData.details"
            style="width: 100%"
            :key="Math.random"
            border
            max-height="240px"
            overflow-y="auto"
          >
            <el-table-column label="节点编号" props="nodeCode" min-width="145">
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.nodeCode'"
                  :rules="rules.sonnodeCode"
                  label-width="0"
                >
                  <el-input
                    v-if="!props.isReadonly"
                    style="width: 120px"
                    v-model="row.nodeCode"
                    placeholder="请输入节点编号"
                    clearable
                  />
                  <span v-else>{{ row.nodeCode }}</span>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="节点名称" props="nodeName" min-width="145">
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.nodeName'"
                  :rules="rules.sonnodeName"
                  label-width="0"
                >
                  <el-input
                    v-if="!props.isReadonly"
                    v-model="row.nodeName"
                    style="width: 120px"
                    placeholder="请输入节点名称"
                    clearable
                  />
                  <span v-else>{{ row.nodeName }}</span>
                </el-form-item>
              </template>
            </el-table-column>
            <!--              <el-table-column label="节点类型" props="nodeType" min-width="150">-->
            <!--                <template #default="{$index,row}">-->
            <!--                  <el-form-item :prop="'details.' + $index + '.nodeType'" :rules="rules.sonnodeType" label-width="0">-->
            <!--                    <el-input v-if="!props.isReadonly" v-model="row.nodeType" placeholder="请输入节点类型" clearable/>-->
            <!--                    <span v-else>{{ row.nodeType }}</span>-->
            <!--                  </el-form-item>-->
            <!--                </template>-->
            <!--              </el-table-column>-->
            <!-- <el-table-column
              label="节点设计参数"
              props="nodeDesignParam"
              min-width="175"
            >
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.nodeDesignParam'"
                  :rules="rules.sonnodeDesignParam"
                  label-width="0"
                >
                  <el-input
                    v-if="!props.isReadonly"
                    v-model="row.nodeDesignParam"
                    placeholder="请输入节点设计参数"
                    style="width: 150px"
                    clearable
                  />
                  <span v-else>{{ row.nodeDesignParam }}</span>
                </el-form-item>
              </template>
            </el-table-column> -->
            <el-table-column
              label="处理器类型"
              props="processorType"
              min-width="170"
            >
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.processorType'"
                  :rules="rules.sonprocessorType"
                  label-width="0"
                  style="width: 145px"
                >
                  <el-select
                    v-if="!props.isReadonly"
                    v-model="row.processorType"
                    clearable
                    placeholder="请选择处理器类型"
                  >
                    <el-option
                      v-for="item in dictionaryStore.filterDictList(
                        'processorType'
                      )"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                  <span v-else>{{
                    dictionaryStore.filterDictName(
                      "processorType",
                      row.processorType
                    )
                  }}</span>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              label="输入主题"
              props="inputTopic"
              min-width="150"
            >
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.inputTopic'"
                  :rules="rules.soninputTopic"
                  label-width="0"
                >
                  <el-input
                    style="width: 130px"
                    v-if="!props.isReadonly"
                    v-model="row.inputTopic"
                    placeholder="请输入输入主题"
                    clearable
                  />
                  <span v-else>{{ row.inputTopic }}</span>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              label="输出主题"
              props="outputTopic"
              min-width="150"
            >
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.outputTopic'"
                  :rules="rules.sonoutputTopic"
                  label-width="0"
                >
                  <el-input
                    style="width: 130px"
                    v-if="!props.isReadonly"
                    v-model="row.outputTopic"
                    placeholder="请输入输出主题"
                    clearable
                  />
                  <span v-else>{{ row.outputTopic }}</span>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="是否启用" props="enabled" min-width="100">
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.enabled'"
                  :rules="rules.enabled"
                  label-width="0"
                >
                  <el-switch
                    style="margin-left: 20px"
                    v-model="row.enabled"
                    :active-value="1"
                    :inactive-value="0"
                    :disabled="props.isReadonly"
                  />
                  <!-- <el-input
                    style="width: 130px"
                    v-if="!props.isReadonly"
                    v-model="row.enabled"
                    placeholder="请输入备注"
                    clearable
                  /> -->
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="备注" props="remarks" min-width="150">
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.remarks'"
                  :rules="rules.sonremarks"
                  label-width="0"
                >
                  <el-input
                    style="width: 130px"
                    v-if="!props.isReadonly"
                    v-model="row.remarks"
                    placeholder="请输入备注"
                    clearable
                  />
                  <span v-else>{{ row.remarks }}</span>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              fixed="right"
              align="center"
              label="操作"
              width="100"
              v-if="!props.isReadonly"
            >
              <template #default="scope">
                <el-button
                  :disabled="formData.details.length < 2"
                  type="danger"
                  link
                  @click.stop="handleDelete(scope.$index)"
                >
                  <i-ep-delete />
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="!props.isReadonly"
            type="primary"
            :loading="loading"
            @click="handleSubmit"
            >确 定
          </el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "ADMINSCACOLLCETFLOWADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

/** 弹窗显示 **/
const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

/** formData定义表单数据 */
const formRef = ref(ElForm);
let formData = reactive({
  id: "",
  version: "",
  flowCode: "",
  flowName: "",
  equipTypeId: "",
  deviceId: "",
  enabled: 1,
  deleted: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  details: [
    {
      id: "",
      version: "",
      flowId: "",
      nodeCode: "",
      nodeName: "",
      nodeType: "",
      nodeDesignParam: "",
      processorType: "",
      inputTopic: "",
      outputTopic: "",
      prevNodeIds: "",
      nextNodeIds: "",
      deleted: "",
      remarks: "",
      enabled: 1,
      createTime: "",
      createdUserId: "",
      createdUserName: "",
      lastUpdateTime: "",
      lastUpdatedUserId: "",
      lastUpdatedUserName: "",
    },
  ],
});

/** rules规则 */
const rules = reactive({
  flowCode: [
    { required: true, message: "请输入采集流程编号", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  flowName: [
    { required: true, message: "请输入采集流程名称", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  equipTypeId: [
    { required: true, message: "请选择设备类型", trigger: "change" },
  ],
  deviceId: [{ required: true, message: "请选择设备", trigger: "change" }],
  enabled: [],
  remarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  sonflowId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  sonnodeCode: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  sonnodeName: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  sonnodeType: [
    { min: 1, max: 20, message: "长度在 1 到 20 个字符", trigger: "blur" },
  ],
  sonnodeDesignParam: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  sonprocessorType: [
    { required: true, message: "请选择处理器类型", trigger: "change" },
  ],
  soninputTopic: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  sonoutputTopic: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  sonremarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
});

const isValidated = ref(false);
/** 删除行 */
const handleDelete = (index: any) => {
  formData.details.splice(index, 1);
  isValidated.value && formRef.value.validate(() => {});
};

const details = {
  id: "",
  version: "",
  flowId: "",
  nodeCode: "",
  nodeName: "",
  nodeType: "",
  nodeDesignParam: "",
  processorType: "",
  inputTopic: "",
  outputTopic: "",
  prevNodeIds: "",
  nextNodeIds: "",
  deleted: "",
  enabled: 1,
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
};

/** 添加行 */
const handleAdd = () => {
  let sondata = JSON.parse(JSON.stringify(details));
  formData.details.push(sondata);
};

/** 编辑时赋值 */
watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      Object.assign(formData, props.data);
      if (formData.id) {
        getdetails();
      }
      if (formData.equipTypeId) {
        deviceTypeChage(formData.equipTypeId);
      }
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  // formData.details = [JSON.parse(JSON.stringify(details))];
  // formData.details = defaultList;
  formData.id = "";
  formData.version = "";
  formData.flowCode = "";
  formData.flowName = "";
  formData.equipTypeId = "";
  formData.deviceId = "";
  formData.enabled = 1;
  formData.deleted = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  equipList.value = [];
  getDefault();
}

const loading = ref(false);

/** 数据采集流程保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      console.log("formData", toRaw(formData));
      await request({
        url: "/iotadmin/scacollcetflow/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
      isValidated.value = false;
    } else {
      isValidated.value = true;
    }
  });
}

async function getdetails() {
  let sondetails = await request({
    url: "/iotadmin/scacollcetflow/getDetails",
    method: "post",
    data: formData,
  }).finally(() => {
    loading.value = false;
  });
  formData.details = sondetails.data;
}

// 获取设备类型下拉框
const equipTypeList: any = ref([]);

async function gettypelist() {
  let types = await request({
    url: "/iotadmin/scaequiptype/getlist",
    method: "post",
    data: {},
  }).finally(() => {
    loading.value = false;
  });
  equipTypeList.value = types.data;
  equipTypeList.value?.map((item: any) => {
    item.label = item.equipTypeName;
    item.value = item.id;
  });
}

const equipList = ref([]);
const deviceTypeChage = async (value: any) => {
  console.log(value);
  if (value) {
    const res = await request({
      url: "/iotadmin/scaequipinfo/getlist",
      method: "post",
      data: { equipTypeId: value },
    });
    if (res.code === 200) {
      equipList.value = res.data;
    }
  } else {
    equipList.value = [];
  }
};

// 获取默认数据
let defaultList: any = [];
async function getDefault() {
  await request({
    url: "/iotadmin/scaCollcetFlow/getDefault",
    method: "get",
  }).then((res) => {
    console.log(res.data);
    defaultList = res.data.details;
    formData.details = res.data.details;
  });
}

onMounted(() => {
  gettypelist();
  getDefault();
});
</script>

<style lang="scss" scoped>
h4 {
  font-weight: 400;
  color: #000;
  padding-left: 10px;
  font-size: 14px;
  line-height: 14px;
}

.formTable {
  :deep(.el-table .el-form-item) {
    padding: 11px 0 0 0 !important;
  }
  :deep(.el-table .el-form-item__error) {
    font-size: 11px !important;
  }
}

:deep(.el-table) {
  // .cell.el-tooltip {
  //   padding: 0 15px;
  // }

  // .el-table__body td.el-table__cell {
  //   padding: 20;
  // }
  // .cell.el-tooltip {
  //   padding: 5px;
  // }
  .el-table__body td.el-table__cell {
    // padding: 5px !important;
    padding: 0 !important;
  }
}

:deep(.search-container .el-input.el-input--default.el-input--suffix) {
  // 固定宽度
  width: 190px !important;
}

:deep(.search-container .el-form-item--default .el-form-item__label) {
  // 固定宽度
  justify-content: end;
}
// :deep(.search-container .formTable .el-form-item--default .el-switch) {
//   // 固定宽度
//   align-items: center;
//   justify-content: center;
// }
.el-switch {
  align-items: center;
  justify-content: center;
}
</style>
